package com.bsh.repository;

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.bsh.mybatis.IRepository.MobileVerifyCodeMapper;
import com.bsh.mybatis.model.MobileVerifyCode;

@Repository
public class DaoMobileVerifyCode {

	@Resource
	SqlSessionTemplate session;
	@Resource
	JdbcTemplate jdbcTemplate;

	MobileVerifyCodeMapper getMapper() {
		return session.getMapper(MobileVerifyCodeMapper.class);
	}

	public int deleteByPrimaryKey(Integer id) {
		int res = getMapper().deleteByPrimaryKey(id);
		return res;
	}

	public int insert(MobileVerifyCode record) {
		int res = getMapper().insert(record);
		return record.getId();
	}

	public int insertSelective(MobileVerifyCode record) {
		int res = getMapper().insertSelective(record);
		return record.getId();
	}

	public MobileVerifyCode selectByPrimaryKey(Integer id) {
		MobileVerifyCode row = getMapper().selectByPrimaryKey(id);
		return row;
	}

	public int updateByPrimaryKeySelective(MobileVerifyCode record) {
		int res = getMapper().updateByPrimaryKeySelective(record);
		return res;
	}

	public int updateByPrimaryKey(MobileVerifyCode record) {
		int res = getMapper().updateByPrimaryKey(record);
		return res;
	}

	/**
	 * 删除过期手机验证码
	 * 
	 * @param mobile
	 * @return
	 * @author jane
	 */
	public int deleteByMobile(String mobile) {
		int res = getMapper().deleteByMobile(mobile);
		return res;
	}

	/**
	 * 新注册时判断手机号是否存在
	 * 
	 * @param mobile
	 * @return
	 * @author jane
	 */
	public int checkUserByMobile(String mobile) {
		int res = getMapper().checkUserByMobile(mobile);
		return res;
	}

	/**
	 * 查询最后一次的手机验证码
	 * 
	 * @param mobile
	 * @return
	 */
	public String findCodeByMobile (MobileVerifyCode record) {
		return getMapper().findCodeByMobile(record);

	}
	/**
	 * 查询ip发送注册验证码次数
	 * @param mobile
	 * @return
	 */
	public int checkIpTimes(String ip) {
		int res = getMapper().checkIpTimes(ip);
		return res;
	}

	/**
	 * 查询设备号发送注册验证码次数
	 * @param mobile
	 * @return
	 *
	 */
	public Integer checkDevTimes(String deviceNum) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT count(1)  FROM  mobile_verify_code ");
		sb.append("WHERE  DATE_FORMAT(create_time,'%Y-%m-%d')=CURDATE()");
		sb.append(String.format("AND device_num='%s'",deviceNum.trim()));
		Integer result = null;
		try {
			result = jdbcTemplate.queryForInt(sb.toString());
		} catch (DataAccessException e) {
			return result;
		}
		return result;
	}
	
	

}
